package utils

import (
	"bufio"
	"bytes"
	"context"
	"errors"
	"fmt"
	"github.com/ngaut/log"
	"os/exec"
)

func EvalScripts(arg string) error {
	cmd := exec.Command("bash", "-c", arg)
	var stdout, stderr bytes.Buffer
	cmd.Stdout = &stdout
	cmd.Stderr = &stderr

	err := cmd.Run()
	if err != nil {
		stderrStr := string(stderr.Bytes())
		if stderrStr == "" {
			stderrStr = err.Error()
		}
		return errors.New(stderrStr)
	}

	return nil
}

func ExecShell(ctx context.Context, program string, flagsToExec []string) error {
	cmd := exec.CommandContext(ctx, program, flagsToExec...)
	stdOut, err := cmd.StdoutPipe()
	if err != nil {
		return err
	}
	stdErr, err := cmd.StderrPipe()
	if err != nil {
		return err
	}

	if err = cmd.Start(); err != nil {
		return err
	}

	go func() {
		scanner := bufio.NewScanner(stdErr)
		for scanner.Scan() {
			line := scanner.Text()
			fmt.Println(line)
		}
		if err := scanner.Err(); err != nil {
			log.Errorf("error reading from stderr: %v", err)
		}
	}()

	go func() {
		scanner := bufio.NewScanner(stdOut)
		for scanner.Scan() {
			line := scanner.Text()
			fmt.Println(line)
		}
		if err := scanner.Err(); err != nil {
			log.Errorf("error reading from stderr: %v", err)
		}
	}()

	if err := cmd.Wait(); err != nil {
		return err
	}

	return nil
}
